package me.winds.infrared.module.basic;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.easyder.wrapper.base.presenter.MvpBasePresenter;
import com.easyder.wrapper.base.view.WrapperMvpActivity;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;
import com.easyder.wrapper.utils.LogUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.permissions.RxPermissions;

import net.launchdigital.irsdk.IrSdk;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import me.winds.infrared.R;
import me.winds.infrared.AppConfig;
import me.winds.infrared.WrapperApplication;
import me.winds.infrared.module.basic.bean.IrBean;
import me.winds.infrared.utils.InfraredUtils;
import me.winds.infrared.widget.floating.FloatingActionButton;
import me.winds.infrared.widget.floating.FloatingActionsMenu;
import me.winds.widget.autolayout.utils.AutoUtils;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/8/21
 * Version: 1.0
 * Desc:
 */

@Deprecated
public class HomeActivity_original extends WrapperMvpActivity<MvpBasePresenter> {

    @BindView(R.id.iv_image)
    ImageView ivImage;
    @BindView(R.id.tv_max_temp)
    TextView tvMaxTemp;
    @BindView(R.id.fab_palette)
    FloatingActionButton fabPalette;
    @BindView(R.id.fab_center_temp)
    FloatingActionButton fabCenterTemp;
    @BindView(R.id.fab_camera)
    FloatingActionButton fabCamera;
    @BindView(R.id.fam_menu)
    FloatingActionsMenu famMenu;


    protected IrSdk irSdk;
    protected IrBean irBean;
    protected int[] imageBuffer = new int[160 * 120];
    protected double[] tempBuffer = new double[320 * 240];

    @Override
    protected int getViewLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected void setImmersionBar() {
        super.setImmersionBar();
        ImmersionBar.with(this).statusBarView(R.id.status_view).init();
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        irBean = new IrBean();
        irSdk = new IrSdk(WrapperApplication.getInstance());
        famMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
            @Override
            public void onMenuExpanded() {

            }

            @Override
            public void onMenuCollapsed() {

            }

            @Override
            public void onMenuStartExpand() {
                delayTimer(300);
            }
        });
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {

    }

    @Override
    protected boolean isUseTitle() {
        return false;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (irSdk != null) {
            irSdk.register();
            startTimer();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (irSdk != null) {
            endTimer();
            irSdk.unregister();
        }
    }

    @Override
    protected void onDestroy() {
        endTimer();
        super.onDestroy();
        if (irSdk != null) {
            try {
                irSdk.destroy();
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onBackPressedSupport() {
        if (famMenu.isExpanded()) {
            famMenu.collapse();
            return;
        }
        super.onBackPressedSupport();
    }

    @OnClick({R.id.fab_palette, R.id.fab_center_temp, R.id.fab_camera})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.fab_palette:
                setPalette();
                break;
            case R.id.fab_center_temp:

                break;
            case R.id.fab_camera:
                takePicture();
                break;
        }
    }


    /**
     * 截取一张图片
     *
     * @return
     */
    protected Bitmap captureImage() {
        if (irSdk != null && irSdk.isIrSdkReady()) {
            Bitmap bitmap = Bitmap.createBitmap(AppConfig.SIZE_WIDTH, AppConfig.SIZE_HEIGHT, Bitmap.Config.ARGB_8888);
            if (0 == irSdk.captureImage(imageBuffer, AppConfig.SIZE_HEIGHT * AppConfig.SIZE_WIDTH * Integer.BYTES,
                    tempBuffer, 320 * 240 * Double.BYTES)) {
                bitmap.setPixels(imageBuffer, 0, AppConfig.SIZE_WIDTH, 0, 0, AppConfig.SIZE_WIDTH, AppConfig.SIZE_HEIGHT);
                return bitmap;
            }
        }
        return null;
    }


    /**
     * 取集合最大值
     *
     * @param arr
     * @return
     */
    public double getMaxTemperature(double[] arr) {
        Arrays.sort(arr);
        return arr[arr.length - 1];
    }


    /**
     * 获取中心点温度
     *
     * @param arr
     * @return
     */
    public double getCenterTemperature(double[] arr) {
        return arr[AppConfig.SIZE_WIDTH * (AppConfig.SIZE_HEIGHT / 2) + (AppConfig.SIZE_WIDTH / 2)];
    }

    public void getScreenCenter() {
        float height = AutoUtils.getScreenHeight() / 2;
        float width = AutoUtils.getScreenWidth() / 2;
    }

    Disposable disposable;

    private void timer(long delay) {
        disposable = Observable.interval(delay, 120, TimeUnit.MILLISECONDS)
                .map(new Function<Long, IrBean>() {
                    @Override
                    public IrBean apply(Long aLong) throws Exception {
                        Bitmap bitmap = captureImage();
                        if (bitmap != null) {
                            irBean.bitmap = bitmap;
                            irBean.ready = true;
                        } else {
                            irBean.ready = false;
                        }
                        return irBean;
                    }
                })
                .filter(new Predicate<IrBean>() {
                    @Override
                    public boolean test(IrBean irBean) throws Exception {
                        return irBean.ready;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<IrBean>() {
                    @Override
                    public void accept(IrBean irBean) throws Exception {
                        if (irBean.bitmap != null) {
                            ivImage.setImageBitmap(irBean.bitmap);
                            tvMaxTemp.setText(String.format("%1$s%2$.2f%3$s", "最高温度", irBean.maxTemp, "℃"));
                            tvMaxTemp.append(String.format("%1$s%2$.2f%3$s", "\n中心温度", irBean.centerTemp, "℃"));
                        }
                    }
                });
    }

    private void startTimer() {
        if (disposable == null || disposable.isDisposed()) {
            timer(0);
        }
    }

    private void endTimer() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    private void takePicture() {
        checkStoragePermission();
    }

    private void takePictureWithPermission() {
        if (irSdk != null && irSdk.isIrSdkReady()) {
            if (irBean.ready) {
                TaskScheduler.execute(new Task<String>() {
                    @Override
                    public String doInBackground() throws InterruptedException {
                        return InfraredUtils.saveImage(irBean.bitmap);
                    }

                    @Override
                    public void onSuccess(String result) {
                        try {
                            File file = new File(result);
                            MediaStore.Images.Media.insertImage(mActivity.getContentResolver(),
                                    file.getAbsolutePath(), file.getName(), null);
                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                    Uri.fromFile(file)));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }

                        LogUtils.info("图片保存在" + result);
                        showToast("图片保存在" + result);
                    }
                });
            } else {
                showToast("保存失败");
            }
        } else {
            showToast("红外设备未连接");
        }
    }


    private void setPalette() {
        if (irSdk != null && irSdk.isIrSdkReady()) {
//            irSdk.setColormap(IrFactory.getFactory().getPaletteNum());
        } else {
            showToast("红外设备未连接");
        }
    }

    private void checkStoragePermission() {
        new RxPermissions(mActivity).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            delayTimer();
                            takePictureWithPermission();
                        } else {
                            showToast("文件读写权限被拒绝");
                        }
                    }
                });
    }

    private void delayTimer(long delay) {
        endTimer();
        timer(delay);
    }

    private void delayTimer() {
        endTimer();
        timer(500);
    }
}
